import el from "element-ui/src/locale/lang/el";

export function isExternal(path) {
    return /^(https?:|mailto:|tel:)/.test(path)
}

export function validUsername(str) {
    const valid_map = ['admin', 'editor']
    return valid_map.indexOf(str.trim()) >= 0
}

export function validURL(url) {
    const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
    return reg.test(url)
}

// 既可以输入http,又可以输入https,还可以输入www
export function validURL2(url) {
    const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/
    return reg.test(url)
}

export function validLowerCase(str) {
    const reg = /^[a-z]+$/
    return reg.test(str)
}

export function validUpperCase(str) {
    const reg = /^[A-Z]+$/
    return reg.test(str)
}

export function validAlphabets(str) {
    const reg = /^[A-Za-z]+$/
    return reg.test(str)
}

export function validEmail(email) {
    const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return reg.test(email)
}

export function isString(str) {
    if (typeof str === 'string' || str instanceof String) {
        return true
    }
    return false
}

export function isArray(arg) {
    if (typeof Array.isArray === 'undefined') {
        return Object.prototype.toString.call(arg) === '[object Array]'
    }
    return Array.isArray(arg)
}

/**
 * 字典获取label
 * value 值 data 数据源
 */
export function codeFilter(value,data) {
    let msg = "";
    if(data){
        data.forEach((item)=>{
            if(item.value == value){
                msg = item.label
            }
        })
    }
    return msg
}


export function timeFilter(date) {
    // 今天 昨天 前天 年月日
    let data = new Date(date); //后台返回的某个时间
    let d = new Date(data).setHours(0, 0, 0, 0);
    let today = new Date().setHours(0, 0, 0, 0);

    let obj = {
        '-86400000': '昨天',
        0: '今天',
        '-172800000': '前天',
    };
    return obj[d - today] || date.substring(0,10);
}

// 限制输入数字 且第一位不能为0
export function check_num(val,str,min,max) {
    // val 值  str 字段（同一页 多次使用区分）
    let license_num = val;
    license_num = license_num.replace(/[^\d]/g, ''); // 清除“数字”和“.”以外的字符
    // 清除最前面的0
    if(str == "start"){
        if(license_num.replace(/\b(0+)/gi,"") > 999999){
            return max
        }
        if(license_num.replace(/\b(0+)/gi,"") < 1){
            return min
        }
        return license_num.replace(/\b(0+)/gi,"");
    }else if(str == "ending"){
        return license_num.replace(/\b(0+)/gi,"");
    }else if(str == "nodeZero"){
        return license_num;
    }else if(str == "2147483647"){
        license_num.replace(/\b(0+)/gi,"")
        if(license_num > 2147483647){
            return 2147483647;
        }else {
            return license_num.replace(/\b(0+)/gi,"")
        }
    }else if(str == "nocClearZero"){
        return license_num
    }else if(str == "oneZero"){
        if (license_num.indexOf("0") !== -1) {
            // let str_ = license_num.substr(license_num.indexOf("0") + 1);
            // if (str_.indexOf("0") != -1) {
            //     license_num = license_num.substr(0, license_num.indexOf("0") + str_.indexOf("0") + 1);
            // }
            license_num = 0
        }
        return license_num
    } else {
        return license_num.replace(/\b(0+)/gi,"")
    }
}

export function numberCheck(num) {
    let str = num;
    const len1 = str.substr(0, 1);
    const len2 = str.substr(1, 1);
    //如果第一位是0，第二位不是点，就用数字把点替换掉
    if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1);
    }
    //第一位不能是.
    if (len1 == ".") {
        str = "";
    }
    //限制只能输入一个小数点
    if (str.indexOf(".") != -1) {
        let str_ = str.substr(str.indexOf(".") + 1);
        if (str_.indexOf(".") != -1) {
            str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
        }
    }
    //只能是数字和小数点
    // eslint-disable-next-line no-useless-escape
    str = str.replace(/[^\d^\.]+/g,'')
    // 小数点后面只能输入2位小数
    // eslint-disable-next-line no-useless-escape
    str = str.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
    return str;
}

/*验证只能输入数字*/
const numberValidate = (rule, value, callback) => {
    if (value) {
        const pattern = /^\d+$/;
        if(!pattern.test(value)) {
            callback(new Error('必须为数字!'));
        } else {
            callback()
        }
    }
    callback();
};
/*验证只能输入中文,英文*/
const chineseAndEnglishValidator = (rule, value, callback) =>{
    var regu = "^[a-zA-Z\u4e00-\u9fa5]+$";
    var re = new RegExp(regu);
    if (value.search(re) != -1){
        callback()
    } else {
        callback(new Error('只能输入中文,英文!'));
    }
};
/*验证姓名：中文、英文字符、数字*/
const nameValidator = (rule, value, callback) =>{
    var pattern = /^[a-zA-Z\u4e00-\u9fa5\d]+$/;
    if (pattern.test(value)){
        callback()
    } else {
        callback(new Error('请输入正确的姓名(应为汉字、字母或数字)!'));
    }
};
/*验证账号：英文字符、数字*/
const accountValidator = (rule, value, callback) =>{
    var pattern = /^[a-zA-Z\d]+$/;
    if (pattern.test(value)){
        callback()
    } else {
        callback(new Error('只能输入字母、数字!'));
    }
};
/*验证商品名称：中文、英文字符、数字*/
const producetNameValidator = (rule, value, callback) =>{
    var pattern = /^[a-zA-Z\u4e00-\u9fa5\d]+$/;
    if (pattern.test(value)){
        callback()
    } else {
        callback(new Error('请输入正确的名称(应为汉字、字母或数字)!'));
    }
};
/*验证电话号码*/
const phoneValidator= (rule, value, callback) => {
    const pattern = /^1[3|4|5|7|8][0-9]\d{8}$/;
    if(value != null && value != "") {
        if(!pattern.test(value)) {
            callback(new Error('请输入正确的手机号!'))
        } else {
            callback()
        }
    }
    else{
        callback();
    }
};

/*验证手机号和座机号*/
const telValidator= (rule, value, callback) => {
    let isPhone = /^(((\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/;
    if(value != null && value != "") {
        if(!isPhone.test(value)) {
            callback(new Error('请输入正确的手机号!'))
        } else {
            callback()
        }
    }else{
        callback();
    }
};

/*验证域名*/
const urlValidator= (rule, value, callback) => {
    let isUrl = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if(isUrl.test(value)){
        callback();
    } else{
        callback(new Error('请输入正确的域名!'))
    }
};

/*身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X */
const cardNoValidator= (rule, value, callback) => {
    let card = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if(card.test(value)){
        callback();
    } else{
        callback(new Error('请输入正确的身份证!'))
    }
};

const licenseValidator= (rule, value, callback) => {
    if(value){
        if(value.length != 18){
            callback(new Error('营业执照编号长度错误！'));
        }
        let reg = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
        if(!reg.test(value)){
            callback(new Error('营业执照编号校验错误！'));
        }
        callback();
    }else{
        callback()
    }
}

/*验证密码*/
const passWordValidate = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入密码'));
    } else {
        if(/[\u4E00-\u9FA5]/g.test(value)) {
            callback(new Error('密码不能设置中文！'));
        }
        else if(value.length < 8) {
            callback(new Error('密码长度为8到16个字符！'));
        }
        else {
            callback();
        }
    }
};

/*长度小于100*/
const maxLength100Validator = (rule, value, callback) => {
    if (value&&value.length > 100) {
        callback(new Error('请输入长度不超过100位的字符！'));
    } else {
        callback();
    }
};

/*金额：小于9位(亿)，两位小数*/
const moneyValidator = (rule, value, callback) => {
    if (value&&value.length > 0){
        const reg = /^(([1-9][0-9]{0,7})|([0]\.\d{1,2})|([1-9][0-9]{0,7}\.\d{1,2}))$/g;
        if(!reg.test(value) || value==0){
            callback(new Error('请输入小于9位，且最多保留两位小数的正数！'));
        } else {
            callback();
        }
    }else{
        callback()
    }
};

/*库存：小于9位(亿)*/
const stockValidator = (rule, value, callback) => {
    if (value&&value.length > 0){
        const reg = /^([1-9][0-9]{0,7})$/g;
        if(!reg.test(value) || value==0){
            callback(new Error('请输入小于9位的正整数！'));
        } else {
            callback();
        }
    }else{
        callback()
    }
};


export function validates (item) {
    const rules = [];
    if (item.required) {
        rules.push({required: true, message: item.msg, trigger: ['blur']});
    }else{
        rules.push({required: false, message: item.msg, trigger: ['blur']});
    }
    if (item.type) {
        const type = item.type;
        switch (type) {
            case 'number':
                rules.push({validator:numberValidate,trigger: ['blur']});
                break;
            case 'passWord':
                rules.push({validator:passWordValidate,trigger: ['blur']});
                break;
            case 'chineseAndEnglish':
                rules.push({validator:chineseAndEnglishValidator,trigger: ['blur']});
                break;
            case 'mobile':
                rules.push({validator:phoneValidator,trigger: ['blur']});
                break;
            case 'tel':
                rules.push({validator:telValidator,trigger: ['blur']});
                break;
            case 'url':
                rules.push({validator:urlValidator,trigger: ['blur']});
                break;
            case 'cardNo':
                rules.push({validator:cardNoValidator,trigger: ['blur']});
                break;
            case 'license':
                rules.push({validator:licenseValidator,trigger: ['blur']});
                break;
            case 'name':
                rules.push({validator:nameValidator,trigger: ['blur']});
                break;
            case 'account':
                rules.push({validator:accountValidator,trigger: ['blur']});
                break;
            case 'producetName':
                rules.push({validator:producetNameValidator,trigger: ['blur']});
                break;
            case 'maxLength100':
                rules.push({validator:maxLength100Validator,trigger: ['blur']});
                break;
            case 'money':
                rules.push({validator:moneyValidator,trigger: ['blur']});
                break;
            case 'stock':
                rules.push({validator:stockValidator,trigger: ['blur']});
                break;
            default:
                rules.push({});
                break;
        }
    }
    return rules;
}
